//
//  HigherOrder_Function_filter_DemoVC.swift
//  APSwift
//
//  Created by jianbo.pei on 2022/9/13.
//

import UIKit

class HigherOrder_Function_filter_DemoVC: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        test1()
        
        test2()
        test3()
        test4()
    }
    
    private func test1() {
        let integers = [1, 2, 3, 4, 5, 6, 7, 8, 9]
        let filteredIntegers = integers.filter({ $0 > 5 })
        debugPrint("filteredIntegers is \(filteredIntegers)")
    }
    
    private func test2() {
        let optionalNumbers: [Int?] = [1, nil, 3, nil, 5]
        let validNumbers = optionalNumbers.compactMap { $0 }
        debugPrint("compactMap - validNumbers is \(validNumbers)")  // [1, 3, 5]
    }
    
    private func test3() {
        let strings = ["1", "2", "three", "4", "five"]
        let numbers = strings.compactMap { Int($0) }
        debugPrint("compactMap - numbers is \(numbers)")  // [1, 2, 4] （"three" 和 "five" 被移除）
    }
    
    private func test4() {
        struct User {
            let name: String?
        }

        let users = [User(name: "Alice"), User(name: nil), User(name: "Bob"), User(name: "Charlie"), User(name: "")]
        let validNames1 = users.compactMap { $0.name }
        let validNames2 = validNames1.filter { !$0.isEmpty }
        let validNames = validNames2.joined(separator: ", ")
        
        debugPrint("compactMap - validNames1 is \(validNames1)")
        debugPrint("compactMap - validNames2 is \(validNames2)")
        debugPrint("compactMap - validNames is \(validNames)")  // "Alice, Bob, Charlie"
    }

}
